package com.aaa.sbm.util;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @FileName: LoginFilter
 * @Description:
 * @Author: 王成林
 * @CreateTime: 2025/7/10 18:24
 * @Version: 1.0.0
 */
@Component
@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("-------------------------经过了登录过滤器-------------------------");
        //强制转换
        HttpServletRequest request =  (HttpServletRequest)servletRequest;
        HttpServletResponse response =  (HttpServletResponse)servletResponse;
        String requestURI = request.getRequestURI();
        System.out.println(requestURI+"---------------------------");
        
        // 放行静态资源和登录相关页面
        if(requestURI.contains("/js/") || 
           requestURI.contains("/css/") || 
           requestURI.contains("/fonts/") ||
           requestURI.contains("/html/login.html") ||
           requestURI.contains("/html/loginup.html") ||  // 添加注册页面
           requestURI.contains("/user/login") ||
           requestURI.contains("/user/register")){       // 添加注册接口
            //放行
            filterChain.doFilter(request,response);
            return;
        }
        
        //获取session用户信息
        Object userInfo = request.getSession().getAttribute("userinfo");
        //判断为空，说明没有登录
        if(userInfo == null){
            System.out.println("-------------------------重定向-------------------------");
            //重定向
            response.sendRedirect("/html/login.html");
        }else{
            //放行
            filterChain.doFilter(request,response);
        }
    }
}
